#!/usr/bin/python2.6

import syncFromJava as serv
import InitConfig as config
import logSendConfig
import commands, os, string
import re
import buildService
import logging
import import_thread
import log_file
import rpcServer
import json

"""
init listion service
"""
a = config.Config()
ip = a.getCobblerIp()
port = a.getCobblerPort()
log_path = a.getLogPath()
os_path = a.getOsPath()
cobbler_usr = a.getCobblerUsr()
cobbler_pwd = a.getCobblerPwd()
logging.basicConfig(filename = log_path, level = logging.DEBUG)
importTHread = import_thread.listionExport()

class advanceCode:
    def __init__(self):
        """
        init process
        """
        self.ip = ip
        self.port = port
        self.log_path = log_path

    def makeServer(self):
        r = serv.RPCServer(self.ip, self.port)
        try:
            output = commands.getoutput("service cobblerd status")
            m = re.split(" |\(|\)", output)
            if (m.__len__() == 6 and m[2] == "pid"):
                cobbled_status = True
                logSendConfig.registerCobblerToWeb(cobbled_status)
            else:
                cobbled_status = False
        except:
            cobbled_status = None

        # log_file.writeTextLog("regist", ip=self.ip, port=self.port, cobbled_status=cobbled_status)

        if cobbled_status:
            r.service([get_cobblerStatus,builderOS,removeOS,exec_install], 0)


def exec_install(jdata):
    """
    data format :

    [
        {"systemName":"centos","profileName":"CentOS-6.5-x86_641","mac":"00:23:5A:95:28:25","ip":"192.168.12.101","interface":"eth0","hostName":"testHOst"},
        {"systemName":"centos","profileName":"CentOS-6.5-x86_641","mac":"00:23:5A:95:28:25","ip":"192.168.12.101","hostName":"serviceHost"}

    ]
    :param jdata:  the same as above
    :return:
    """
    service, token = rpcServer.getCobblerService()
    data = json.loads(jdata)
    system_message = []
    for i in range(len(data)):
        systems = data[i]
        systemName = systems["systemName"]
        profileName = systems["profileName"]
        mac = systems["mac"]
        clientIp = systems["ip"]

        try:
            hostName = systems["hostName"]
            if hostName == "":
                hostName = "adminHost"
        except:
            hostName = "adminHost"
        try:
            interface = systems["interface"]
        except :
            interface ="eth0"
        system_id = service.new_system(token)
        a = service.modify_system(system_id, "name", systemName, token)
        b = service.modify_system(system_id, "profile", profileName , token)
        c = service.modify_system(system_id, 'modify_interface', {
            "macaddress-eth0": mac,
            "ipaddress-eth0": clientIp,
        }, token)
        d = service.modify_system(system_id, "hostname", hostName, token)
        f = service.save_system(system_id, token)
        if a and b and c and d and f :
            add_system =True
        else:
            add_system = False
        g = service.sync(token)
        temp = '{"systemName":"%s","addStatus":"%s","addName":"%s","addProfileName":"%s","interface":"%s","addHostName":"%s"}'%(systemName,str(add_system),a,b,c,d)
        system_message.append(temp)

    return '{"add_system":"1","message":"%s"}'%(str(system_message))

def get_cobblerStatus():
    """
    get cobbler status
    :return:
    """
    try:
        output = commands.getoutput("service cobblerd status")
        m = re.split(" |\(|\)", output)
        if (m.__len__() == 6 and m[2] == "pid"):
            cobbled_status = 1
        else:
            cobbled_status = 0
    except:
        cobbled_status = 0

    return cobbled_status

def builderOS(osList):
    """
    :param OSName:  os full name
    :param importName:  import name  must be end by arch , exmaple : CentOS-6.5-x86_64
    :param arch:  x86_64 or x86
    :return:  import type
    """
    for i in range(len(osList)):
        osEv = osList[i]
        taskId = osEv['taskId']
        OSName=osEv['OSName']
        arch = osEv['arch']
        buildService.pushOsFile(taskId,OSName,"/usr/local/src/%s"%(OSName),arch)

def removeOS(OSName,importName=None):
    """
    remvoe os system with OSName or importName
    :param OSName: OSName
    :param importName: importName should be unique,so if you don't know this name ,please don't input it.
    :return: remove status!
    """
    if importName == None:
        importName = OSName[:OSName.rfind(".")]

    server ,token =rpcServer.getCobblerService()
    profileStatus = server.remove_profile(importName,token)
    # if profileStatus:
    distroStatus = server.remove_distro(importName,token)
        # if not distroStatus:
        #     log_file.writeTextLog("removeOS", content="remove distro of %s error with importName :%s\n" % (OSName,importName))
        #     return '{"removeOSType":"0","message":"remove distro of %s error!"),"removeTypeName":"error"}'%(OSName)
    # else:
        #remove profile error
        # log_file.writeTextLog("removeOS", content="remove profile of %s error with importName :%s\n" % (OSName,importName))
        # return '{"removeOSType":"0","message":"remove profile of %s error!","buildTypeName":"error"}'%(OSName)

    log_file.writeTextLog("removeOS", content="remove %s with importName :%s , remove profile status : %s , remove distro status : %s\n" % (OSName,importName,profileStatus,distroStatus))
    return '{"removeOSType":"1","message":"remove %s with importName :%s , remove profile status : %s , remove distro status : %s","removeTypeName":"%s"}'%(OSName,importName,profileStatus,distroStatus,distroStatus)


a = advanceCode()
a.makeServer()
# osList=[{'taskId':'test_redhat','OSName':'rhel-6.5-x86_64.iso','arch':'x86_64'},{'taskId':'test_centos','OSName':'CentOS-4.5-x86_64.iso','arch':'x86_64'}]
# osList=[{'taskId':'test_centos','OSName':'CentOS-6.5-x86_64.iso','arch':'x86_64'}]
# builderOS(osList)
